// 菜单管理 sys_menu
const db = require("../db");
const { getNowTime, formatTime } =  require("../utils/index")

/**
 * 新增菜单
 * @param {*} req 
 * @param {*} res 
 */
exports.addMenu = (req, res) => {
    // 日期时间格式化
    req.body.create_time = req.body.create_time ? formatTime(req.body.create_time) : getNowTime();
    // 查询
    const selectSql = `select * from sys_menu where code = ? or name = ?`;
    db.query(selectSql, [req.body.code, req.body.name],(err, results) => {
        if(err) return res.new_send(err);
        // 判断菜单名称和菜单编码是否存在
        if (results.length >= 2) return res.new_send("菜单名称与菜单编码已被占用");
        if (results.length === 1) {
            const { code,  name } = results[0];
            const { code: menu_code, name: menu_name } = req.body;
            if (code === menu_code && name === menu_name) {
              return res.new_send("菜单名称与菜单编码已被占用");
            }
            if (name === menu_name) {
              return res.new_send("菜单名称已被占用");
            }
            if (code === menu_code) {
              return res.new_send("菜单编码已被占用");
            }
          }
        //   插入数据库
        const insertSql = `insert into sys_menu set ?`;
        db.query(insertSql, req.body, (err, results) => {
            if (err) return res.new_send(err);
            if (results.affectedRows !== 1) return res.new_send("新增菜单失败");
            res.send({
              status: 0,
              message: "新增菜单成功",
              data: { insertId: results.insertId },
            });
          });
    })
}

/**
 * 修改菜单
 * @param {*} req 
 * @param {*} res 
 */
exports.updateMenu = (req, res) => {
  // 日期时间格式化
  req.body.create_time = req.body.create_time ? formatTime(req.body.create_time) : getNowTime();
  // 查询
  const selectSql = `select * from sys_menu where id <> ? and (code = ? or name = ?)`;
  db.query(
    selectSql,
    [req.body.id, req.body.code, req.body.name],
    (err, results) => {
      if (err) return res.new_send(err);
      // 判断菜单名称和菜单编码是否存在
      if (results.length >= 2) return res.new_send("菜单名称与菜单编码已被占用");
      if (results.length === 1) {
        const { code, name } = results[0];
        const { code: menu_code, name: menu_name } = req.body;
        if (code === menu_code && name === menu_name) {
          return res.new_send("菜单名称与菜单编码已被占用");
        }
        if (name === menu_name) {
          return res.new_send("菜单名称已被占用");
        }
        if (code === menu_code) {
          return res.new_send("菜单编码已被占用");
        }
      }

      // 修改数据库
      const updateSql = `update sys_menu set ? where Id = ?`;
      db.query(updateSql, [req.body, req.body.id], (err, results) => {
        if (err) return res.new_send(err);
        if (results.affectedRows !== 1) return res.new_send("更新菜单失败");
        //todo: 处理操作日志表
        res.new_send("更新菜单成功", 0);
      });
    })
}

/**
 * 修改菜单_是否移动端
 * @param {*} req 
 * @param {*} res 
 */
exports.updateMenu_isMobile = (req, res) => {
  const { id, is_mobile } = req.body;
  const updateSql = `update sys_menu set is_mobile = ? where id = ?`;
  db.query(updateSql, [is_mobile, id], (err, results) => {
    if (err) return res.new_send(err);
    if (results.affectedRows <= 0) return res.new_send("更新状态失败");
    res.new_send("更新状态成功", 0);
  });
}

/**
 * 修改菜单_是否电脑端
 * @param {*} req 
 * @param {*} res 
 */
exports.updateMenu_isPc = (req, res) => {
  const { id, is_pc } = req.body;
  const updateSql = `update sys_menu set is_pc = ? where id = ?`;
  db.query(updateSql, [is_pc, id], (err, results) => {
    if (err) return res.new_send(err);
    if (results.affectedRows <= 0) return res.new_send("更新状态失败");
    res.new_send("更新状态成功", 0);
  });
}

/**
 * 修改菜单_是否管理员
 * @param {*} req 
 * @param {*} res 
 */
exports.updateMenu_isAdmin = (req, res) => {
  const { id, is_admin } = req.body;
  const updateSql = `update sys_menu set is_admin = ? where id = ?`;
  db.query(updateSql, [is_admin, id], (err, results) => {
    if (err) return res.new_send(err);
    if (results.affectedRows <= 0) return res.new_send("更新状态失败");
    res.new_send("更新状态成功", 0);
  });
}

/**
 * 根据Id删除菜单
 * @param {*} req 
 * @param {*} res 
 */
exports.deleteMenuById = (req, res) => {
  const deleteSql = `update sys_menu set is_delete = 1 where id = ?`;
  db.query(deleteSql, req.params.id, (err, results) => {
    if (err) return res.new_send(err);
    if (results.affectedRows <= 0) return res.new_send("删除菜单失败");
    res.new_send("删除菜单成功", 0);
  });
};

/**
 * 获取菜单列表
 * @param {*} req 
 * @param {*} res 
 */
exports.getMenuLsit = (req, res) => {
  // 分页加载
  const page_num = req.query.page_num || 1  //当前的num
  const page_size = req.query.page_size || 10  //当前页的数量
  const params = [(parseInt(page_num) - 1) * parseInt(page_size), parseInt(page_size)]
  // 查询
  const selectSql = `select * from sys_menu where is_delete = 0 limit ?,?`;
  db.query(selectSql, params, (err, results) => {
    if (err) return res.new_send(err);
    if (results.length > 0) {
      results.forEach((item) => {
        item.create_time = formatTime(item.create_time);
      });
    }
    // 列表数据
    let menus = results

    // 查询数据库总数
    const totalSql = 'select count(*) as total from sys_menu where is_delete = 0'
    db.query(totalSql, (err, results) => {
      if (err) return res.new_send(err);
      let total = results[0]['total'] // 总数
      res.send({
        status: 0,
        message: "获取菜单成功",
        total,
        data: menus,
      });
    })
  });
}

/**
 * 根据Id获取菜单信息
 * @param {*} req 
 * @param {*} res 
 */
exports.getMenuById = (req, res) => {
  const selectSql = `select * from sys_menu where id = ?`;
  db.query(selectSql, req.params.id, (err, results) => {
    if (err) return res.new_send(err);
    if (results.length > 0) {
      results.forEach((item) => {
        item.create_time = formatTime(item.create_time);
      });
    }
    res.send({
      status: 0,
      message: "获取菜单成功",
      data: results,
    });
  });
}

/**
 * 获取菜单父级列表
 * @param {*} req 
 * @param {*} res 
 */
exports.getMenuParent = (req, res) => {
  const selectSql = `select * from sys_menu where parent_id = 0 and is_delete = 0 order by order_num`;
  db.query(selectSql, (err, results) => {
    if (err) return res.new_send(err);
    if (results.length > 0) {
      results.forEach((item) => {
        item.create_time = formatTime(item.create_time);
      });
    }
    res.send({
      status: 0,
      message: "获取菜单成功",
      data: results,
    });
  });
}

/**
 * 获取菜单子级列表
 * @param {*} req 
 * @param {*} res 
 */
exports.getMenuChild = (req, res) => {
  const selectSql = `select * from sys_menu where parent_id != 0 and is_delete = 0 order by order_num`;
  db.query(selectSql, (err, results) => {
    if (err) return res.new_send(err);
    if (results.length > 0) {
      results.forEach((item) => {
        item.create_time = formatTime(item.create_time);
      });
    }
    res.send({
      status: 0,
      message: "获取菜单成功",
      data: results,
    });
  });
}

/**
 * 获取菜单树形列表
 * @param {*} req 
 * @param {*} res 
 */
exports.getMenuTree = (req, res) => {
  const selectSql = `select * from sys_menu where is_delete = 0 order by order_num`;
  db.query(selectSql, (err, results) => {
    if (err) return res.new_send(err);
    results.forEach((item) => {
      item.create_time = formatTime(item.create_time);
    });
    const result = results.reduce((prev, curr, i, arr) => {
      curr.children = arr.filter((v) => v.parent_id === curr.id);
      if (curr.parent_id === 0) {
        prev.push(curr);
      }
      return prev;
    }, []);
    // 成功
    res.send({
      status: 0,
      message: "获取菜单成功",
      data: result,
    });
  });
};
